package com.Image.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
import com.Image.util.CdnUtils;
import com.Image.util.FileMd5;
import com.Image.util.utiltoor;


 


@Service
public class uploadImageService implements uploadImageInterface {
	Logger logger = Logger.getLogger(uploadImageService.class);
	@Autowired
	private JdbcTemplate jdbcTemplateCrm;

	/**
	 * 读取本地的文件
	 * 
	 * @Title: readImage
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws FileNotFoundException
	 * @throws @author
	 *             kiwishang
	 * @date 2017年12月18日 下午3:33:22
	 */
	@Override
	public String readImage(HttpServletRequest request) {
		File root = new File("F:/穿衣搭配1");
		List<File> files = new ArrayList<File>();
		if (!root.isDirectory()) {
			files.add(root);
		} else {
			File[] subFiles = root.listFiles();
			int index = 0;
			for (File f : subFiles) {
				boolean iserror=false;
				boolean isgoon=false;
				// 图集的封面照片
				String atlasFirstname = "";
				String atlasFirstnameMD5 = "";
				String issimi="1";
				if(index%3==0 || index%2==0){
					issimi="2";
				}
				List<File> fileslishi = new ArrayList<File>();
				//files.addAll(utiltoor.getFiles(f.getAbsolutePath()));
				fileslishi.addAll(utiltoor.getFiles(f.getAbsolutePath()));
				//需要删除图片小于750*500的图片
				if(fileslishi.size()>0){
					for(int x=0;x<fileslishi.size();x++){
						BufferedImage bi = null;
						try {
						bi = ImageIO.read(fileslishi.get(x));
						logger.info("...............读取的图片地址："+fileslishi.get(x).getAbsolutePath());
						int width = bi.getWidth();
						int height = bi.getHeight();
						if(width<750 && height<500){
							fileslishi.remove(x);
						}
						} catch (IOException e) {
							iserror=true;
						}finally{
							isgoon=iserror;
						}
					}
				}
				//如果有错误的图片直接跳过去
				if(iserror){
					fileslishi.clear();
					break;
				}
				//文件夹下需要有大于10张的图片
				if (fileslishi.size() >= 10) {
					// 查询上次的code取得自增数的开始值
					String indexsql = "select atlasCode from image_atlas order by opretaTime desc limit 0,1 ";
					List<Map<String, Object>> indexlist = jdbcTemplateCrm.queryForList(indexsql);
					if (indexlist != null && indexlist.size() > 0) {
						String indexcode = indexlist.get(0).get("atlasCode").toString();
						String indexarr[] = indexcode.split("_");
						index = Integer.parseInt(indexarr[1]) + 1;
					}
					String imagecodeT = "XIANGGUA_" + index;
					String imageTitle = getRandom();
					
					for (int m = 0; m < fileslishi.size(); m++) {
						String imageCode = imagecodeT + "_" + m;
						String imageAuth = "";
						String imageUrl = "";
						String imageName = "";
						String isfirstImage = "";
						String imageMD5 = "";
						Boolean isfirst=false;
						//替换名字
						// 设置封面照
						if (m == 0) {
							isfirstImage = "1";
							isfirst=true;
						} else {
							isfirstImage = "0";
							isfirst=false;
						}
						// 前五张免费
						//if (m == 0 || m == 1 || m == 2 || m == 3 || m == 4) {
							//imageAuth = "1";
						//} else {
							imageAuth = "1";
						//}
						//上传到linux服务器，先判断是否已经存在
						String newfilename="";
						imageMD5 = FileMd5.getFileMD5(fileslishi.get(m));
						String querysql = "select count(1) as countnum from image_info where imageMD5 ='" + imageMD5+ "'";
						List<Map<String, Object>> numlist = jdbcTemplateCrm.queryForList(querysql);
						if (Integer.parseInt(numlist.get(0).get("countnum").toString()) == 0) {
							newfilename=CdnUtils.sendFile(fileslishi.get(m), isfirst);
							 // 存入本地数据库信息
							imageUrl = "http://image.51jinyinhua.com/" + newfilename;
							if (m == 0) {
								atlasFirstname = "http://image.51jinyinhua.com/XG-500-" + newfilename;;
								atlasFirstnameMD5 = FileMd5.getFileMD5(fileslishi.get(m));
							}
						   // 保存入库,先查询库里是否有这个路径的图片
							String insertsql = "insert into image_info (imageAtlasCode,imageAuth,imageUrl,imageName,isfirstImage,imageMD5,opreatetime,isSNT) values ('"
										+ imageCode + "','" + imageAuth + "','" + imageUrl + "','"
										+ imageName + "','" + isfirstImage + "','" + imageMD5 + "',now(),'0')";
								jdbcTemplateCrm.execute(insertsql);
								logger.info("图片入库：....."+imageCode+"............");
							}
						}
					// 保存图集信息
					String querysql = "select count(1) as countnum from image_atlas where atlasImageMD5 ='"
							+ atlasFirstnameMD5 + "'";
					List<Map<String, Object>> numlist = jdbcTemplateCrm.queryForList(querysql);
					if (Integer.parseInt(numlist.get(0).get("countnum").toString()) == 0) {
						String inseratlassql = "insert into image_atlas (atlasName,atlasCode,firstImage,atlasImageMD5,opretaTime,imageTital,atlasType,atlasPrice) values ('"
								+ utiltoor.getFileName(f.getName()) + "','" + imagecodeT + "','" +atlasFirstname
								+ "','"+atlasFirstnameMD5+"',now(),'"+imageTitle+"','"+issimi+"',1.00)";
						jdbcTemplateCrm.execute(inseratlassql);
						logger.info("图集入库：....."+index+"............");
					}
				}
				fileslishi.clear();
				
			}
		}
        return "success";
	}

	/**
	 * 获取图集
	 */
	@Override
	public ModelAndView getAtlas(HttpServletRequest request) {
		String atlasName=request.getParameter("atlasName");
		String atlasTags=request.getParameter("atlasTags");
		String isDelete=request.getParameter("isDelete");
		String page = request.getParameter("currentPage")==null?"1":request.getParameter("currentPage");// 传过来的页数
		int lineSize = 10; // 每页显示记录10条数
		int pageCount = 0; // 总页数
		int count = 0; // 数据总数
		int currentPage = 1; // 当前是第几页,默认是第一页
		if (page == null || "1".equals(page)) {
		} else {
			currentPage = Integer.parseInt(page); // 当前是第几页,默认是第一页
		}
		if(currentPage<1){
			currentPage = 1;
		}
		StringBuffer sbstr=new StringBuffer();
		sbstr.append("select A.ID,A.atlasName,A.atlasCode, A.imageTital,A.firstImage,A.isDelete,A.atlasPrice from image_atlas  A  where 1=1 ");
		if(atlasName!=null && !atlasName.equals("")){
			sbstr.append(" and A.atlasName like '%"+atlasName+"%' ");
		}
		if(atlasTags!=null && !atlasTags.equals("")){
			sbstr.append(" and A.imageTital like '%"+atlasTags+"%' ");
		}
		if(isDelete!=null && !isDelete.equals("")){
			sbstr.append(" and A.isDelete = '"+isDelete+"' ");
		}
		sbstr.append(" limit " + (currentPage - 1) * lineSize + ","+ lineSize);
		String querysql=sbstr.toString();
		List<Map<String, Object>> imagelist = jdbcTemplateCrm.queryForList(querysql);
		//获取总数
		StringBuffer countstr=new StringBuffer();
		countstr.append("select count(1) as total from image_atlas where 1=1 ");
		if(atlasName!=null && !atlasName.equals("")){
			countstr.append(" and atlasName like '%"+atlasName+"%' ");
		}
		if(atlasTags!=null && !atlasTags.equals("")){
			countstr.append(" and imageTital like '%"+atlasTags+"%' ");
		}
		if(isDelete!=null && !isDelete.equals("")){
			countstr.append(" and isDelete = '"+isDelete+"' ");
		}
		
		String querytotal=countstr.toString();
		List<Map<String, Object>> totallist = jdbcTemplateCrm.queryForList(querytotal);
		count=Integer.parseInt(totallist.get(0).get("total").toString());
		int temp = count / lineSize; // 取商
		int tem2=count%lineSize;//取余数
		if (tem2 <lineSize && tem2>0 && temp>0 ) {
			pageCount = count / lineSize + 1; // 总页数
		}else if(tem2==0 && temp>0){
			pageCount = temp;
		}else {
			pageCount = 1; // 总页数
		}
		if(currentPage>=pageCount){
			currentPage=pageCount;
		}
		
		//对list里的数据进行二次处理
		if(imagelist!=null && imagelist.size()>0){
			for(int i=0;i<imagelist.size();i++){
				//获取标签
				String tagname=imagelist.get(i).get("imageTital").toString();
				String  tagnamearr []=tagname.split(",");
				String tagNmaestr="'";
				for(int m=0;m<tagnamearr.length;m++){
					tagNmaestr+=tagnamearr[m]+"','";
				}
				tagNmaestr=tagNmaestr.substring(0,tagNmaestr.length()-2);
				String querytagnamesql="SELECT tagName FROM tag_config WHERE tagCode IN ("+tagNmaestr+") and isShow=0 and isDelete=0";
				List<Map<String, Object>> taglist=jdbcTemplateCrm.queryForList(querytagnamesql);
				String tagnamenew="";
				if(taglist!=null && taglist.size()>0){
					for(int n=0;n<taglist.size();n++){
						tagnamenew+="<input type=\"button\" style=\"background-color: #F0FFFF\"  value=\""+taglist.get(n).get("tagName").toString()+"\" )>";
					}
				}
				imagelist.get(i).put("imageTital", tagnamenew);
				
			}
		}
		
		ModelAndView mView = new ModelAndView("/view/getAtlas");
		mView.addObject("imagelist", imagelist);
		mView.addObject("pageCount", pageCount);
		mView.addObject("currentPage", currentPage);
		mView.addObject("count", count);
		
		mView.addObject("atlasName", atlasName);
		mView.addObject("atlasTags", atlasTags);
		mView.addObject("isDelete", isDelete);
		return mView;
	}

	
	/**
	 * 获取图集下所有的图片
	 */
	@Override
	public ModelAndView getAllinfo(HttpServletRequest request, String imageCode) {
		String querysql="select ID,imageUrl from image_info where imageAtlasCode  LIKE '" + imageCode+"/_%' escape'/'  and isSNT='0' and isDelete='0'";
		List<Map<String, Object>> infolist=jdbcTemplateCrm.queryForList(querysql);
		logger.info("该图集共"+infolist.size()+"张图片");
		ModelAndView mView=new ModelAndView("/view/getEveryAllinfo");
		mView.addObject("infolist", infolist);
		Map<String, Object> firstimage=infolist.get(0);
		mView.addObject("firstimage", firstimage);
		mView.addObject("imageNum", infolist.size());
		return mView;
	}
	/**
	 * 随机获去标签
	* @Title: getRandom 
	* @Description: TODO
	* @param @return    
	* @return int    
	* @throws 
	* @author kiwishang 
	* @date 2017年12月22日 下午3:17:20
	 */
	
	public  String getRandom(){
		String tagname="SELECT tagCode FROM tag_config WHERE isShow='0' AND isDelete='0'";
		List<Map<String,Object>> namelist=jdbcTemplateCrm.queryForList(tagname);
		int max = namelist.size();
        int min = 1;
        Random random = new Random();
        int s = random.nextInt(max)%(max-min+1);
        return namelist.get(s).get("tagCode").toString();
    }
    
	/**
	 * 下架图集
	 */
	@Override
	public int deleteImages(String atlasCodes,String czcode) {
		//下架图集，同时把该图集下的照片也下架
		String updatesql="";
		String updatesql2="";
		if(czcode.equals("SJ")){
			 updatesql="update image_atlas set isDelete='0' where atlasCode in ("+atlasCodes+")";	
			 updatesql2="update image_info set isDelete='0' where imageAtlasCode like '" + atlasCodes.replaceAll("'", "")+"/_%' escape'/'";
		}
		if(czcode.equals("XJ")){
			updatesql="update image_atlas set isDelete='1' where atlasCode in ("+atlasCodes+")";	
			 updatesql2="update image_info set isDelete='1' where imageAtlasCode like '" + atlasCodes.replaceAll("'", "")+"/_%' escape'/'";
		}
		int m=jdbcTemplateCrm.update(updatesql);
		int n=jdbcTemplateCrm.update(updatesql2);
		if(m>0 && n>0){
			return 1;
		}else{
			return 0;
		}
		
	}
    
	/**
	 * 修改图集名称
	 */
	@Override
	public int updateAtlasName(String dataid, String updatname) {
		String updatesql="update image_atlas set atlasName='"+updatname+"' where ID="+dataid;
		int m=jdbcTemplateCrm.update(updatesql);
		return m;
	}

	
	/**
	 * 获取图片的标签
	 */
	@Override
	public List<Map<String, Object>> getTagList() {
		String querysql="select * from tag_config where isShow=0 and isDelete=0";
		List<Map<String, Object>> taglist=jdbcTemplateCrm.queryForList(querysql);
		return taglist;
	}

	/**
	 * 修改标签
	 */
	@Override
	public int updateAtlasTag(String dataid, String tagNames) {
		String updatesql="update image_atlas set imageTital='"+tagNames+"' where ID in ("+dataid+")";
		int m=jdbcTemplateCrm.update(updatesql);
		return m;
	}
     
	/**
	 * 修改图集的单价
	 */
	@Override
	public int updateAtlasPrice(String dataid, String tagPrice) {
		String updatesql="update image_atlas set atlasPrice="+tagPrice+" where ID in ("+dataid+")";
		int m=jdbcTemplateCrm.update(updatesql);
		return m;
	}
   
	/**
	 * 轮播图设置
	 */
	@Override
	public ModelAndView bannerSet() {
		String selectsql="select * from image_atlas where isDelete=0 ";
		List<Map<String, Object>> bannerlist=jdbcTemplateCrm.queryForList(selectsql);
	/*	if(bannerlist!=null && bannerlist.size()>0){
			for(int i=0;i<bannerlist.size();i++){
				String filename=bannerlist.get(i).get("firstImage").toString();
				String [] dilenamearr=filename.split("/");
				bannerlist.get(i).put("firstImage", dilenamearr[5]+"/"+dilenamearr[6]);
			}
		}*/
		
		ModelAndView mView =new ModelAndView("/view/bannerSet");
		mView.addObject("bannerlist", bannerlist);
		mView.addObject("firstimage", bannerlist.get(0).get("firstImage"));
		return mView;
	}

	/**
	 * 保存设置的轮播图
	 */
	@Override
	public int saveBanner(String ischeckedimg) {
		int m=0;
		String checkimgarr []=ischeckedimg.split(",");
		//先判断里面是否已经有,存在的话 先删除
		String ishavesql="select count(1) as num from home_page_banner ";
		List<Map<String, Object>> countlist=jdbcTemplateCrm.queryForList(ishavesql);
		if(Integer.parseInt(countlist.get(0).get("num").toString())>0){
			String deletesql="delete  from home_page_banner";
			jdbcTemplateCrm.execute(deletesql);
		}
		if(checkimgarr.length>0){
			for(int i=0;i<checkimgarr.length;i++){
				String querysql="select firstImage from image_atlas where atlasCode='"+checkimgarr[i]+"'";
				Map<String,Object> imagemap=jdbcTemplateCrm.queryForMap(querysql);
				String insertsql="INSERT INTO home_page_banner(atlasNo,url,sort,state,timestamp)values ('"+checkimgarr[i]+"','"+imagemap.get("firstImage").toString().replace("XG-500-", "XG-750-")+"',"+(i+1)+",1,now())";
				 m=jdbcTemplateCrm.update(insertsql);
			}
		}
		return m;
	}
   /**
    * 版本控制
   * @Title: appVersionset 
   * @Description: TODO
   * @param @param request
   * @param @return    
   * @return int    
   * @throws 
   * @author kiwishang 
   * @date 2017年12月27日 上午10:44:27
    */
	@Override
	public int appVersionset(HttpServletRequest request) {
		  String uploadPath = "D:/uploadimage"; // 上传文件的目录  
		  File tempPathFile = null;  
		  int m=0,n=0;
		   //String serviceVersion=request.getParameter("serviceVersion");
		   //String updateContent=request.getParameter("updateContent");
		   //String isForce=request.getParameter("isForce");
		try{
		 // Create a factory for disk-based file items  
        DiskFileItemFactory factory = new DiskFileItemFactory();  

        // Set factory constraints  
        factory.setSizeThreshold(4096); // 设置缓冲区大小，这里是4kb  
        factory.setRepository(tempPathFile);// 设置缓冲区目录  

        // Create a new file upload handler  
        ServletFileUpload upload = new ServletFileUpload(factory);  

        // Set overall request size constraint  
        upload.setSizeMax(4194304*10); // 设置最大文件尺寸，这里是4MB  

        List<FileItem> items = upload.parseRequest(request);// 得到所有的文件  
        Iterator<FileItem> i = items.iterator();  
        while (i.hasNext()) {  
            FileItem fi = (FileItem) i.next();  
            String fileName = fi.getName();  
            if (fileName != null) {  
                File fullFile = new File(new String(fi.getName().getBytes(), "utf-8")); // 解决文件名乱码问题  
                File savedFile = new File(uploadPath, fullFile.getName());  
                fi.write(savedFile);  
                String saveurl=uploadPath+"/"+fullFile.getName();
                //将数据入库
                String insertsql="insert into  user_app_update(serviceVersion,updateContent,updateURL,isForce,updateTime,type)"
                		+ " values('linux','','"+saveurl+"',0,now(),0)";
                n=jdbcTemplateCrm.update(insertsql);
                logger.info("。。。。。版本信息入库成功。。。。。");
            }  
            m=1;
        }  
        
    } catch (Exception e) {  
        e.printStackTrace();
        m=0;
    }  
		return m+n;
	}
/**
 * 下架单张图片
 */
@Override
public int deleteImagebyOne(String deletekey) {
	String updatesql="update image_info set isDelete='1' where imageUrl='"+deletekey+"'";
	int m=jdbcTemplateCrm.update(updatesql);
	return m;
}
	
	
	

}
